import {
	createRouter,
	createWebHistory
} from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: [
		{
			path: "/login",
			name: 'login',
			component: () => import("../views/Login.vue")
		},
		{
			path: '/',
			name: 'home',
			component: HomeView,
			redirect:"/homepage",
			// children:[{
			// 	path:"/homepage",
			// 	component:()=>import ("../views/homepage.vue")
			// }]
		}	
	]
})
import { FindMenu } from '@/api/wym'

// console.log(menuRes)

//全局前置守卫；

router.beforeEach(async (to,from)=>{
	if(to.name!='login' && !sessionStorage.getItem("token")){
		return {name:"login"}
	}
	if(!sessionStorage.getItem("token")){
		return 
	}
	
	if(router.getRoutes().length==2){
		let menuRes=await FindMenu({
			roleIds:[1]
		})
		// console.log('mes',menuRes)
		menuRes.forEach(first=>{
			// console.log("first",first)
			let firstMenuName=first.path
			firstMenuName=firstMenuName.substring(1);//一级菜单名称
			router.addRoute('home',{
				name:firstMenuName,
				path:first.path,
				component:()=>import(`../views/${firstMenuName}.vue`)
			})
			// console.log(first)
			if(first.childs && first.childs.length!=0){
				// console.log(first.childs)
				
				first.childs.forEach(second=>{
					let secondMenuName=second.path.split("/")
					// console.log(secondMenuName[secondMenuName.length-1])
					secondMenuName=secondMenuName[secondMenuName.length-1]
					var routeObj={
						name:firstMenuName+"_"+secondMenuName,
						path:secondMenuName,
						component:()=>import(`../views/${secondMenuName}.vue`),
					}
					//console.log('obj',routeObj)
					router.addRoute('home',routeObj)
				})
			}
		})
		// console.log('getRoutes',router.getRoutes())
		router.replace(to.path)
	}

	
})

export default router



